package com.dlc.shop.user.api.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.dlc.shop.bean.app.dto.DvyTypeDTO;
import com.dlc.shop.bean.app.dto.ShopCartDto;
import com.dlc.shop.bean.app.dto.ShopCartItemDto;
import com.dlc.shop.bean.app.dto.ShopCartOrderMergerDto;
import com.dlc.shop.bean.app.param.OrderParam;
import com.dlc.shop.bean.enums.DvyType;
import com.dlc.shop.bean.enums.OrderType;
import com.dlc.shop.bean.vo.UserDeliveryInfoVO;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.CacheManagerUtil;
import com.dlc.shop.delivery.api.manager.DeliveryOrderManager;
import com.dlc.shop.manager.OrderUseScoreManager;
import com.dlc.shop.manager.UserLevelOrderManager;
import com.dlc.shop.manager.impl.ConfirmOrderManager;
import com.dlc.shop.manager.impl.ShopCartAdapter;
import com.dlc.shop.manager.impl.ShopCartItemAdapter;
import com.dlc.shop.security.api.util.SecurityUtils;
import com.dlc.shop.service.ProductService;
import com.dlc.shop.service.SkuService;
import com.dlc.shop.service.UserExtensionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author LHD
 */
@RestController
@AllArgsConstructor
@RequestMapping("/p/score" )
@Tag(name = "积分商品订单接口")
public class ScoreOrderController {

    private final UserExtensionService userExtensionService;
    private final ProductService productService;
    private final CacheManagerUtil cacheManagerUtil;
    private final SkuService skuService;
    private final ShopCartAdapter shopCartAdapter;
    private final ShopCartItemAdapter shopCartItemAdapter;
    private final ConfirmOrderManager confirmOrderManager;
    private final DeliveryOrderManager deliveryOrderManager;
    private final UserLevelOrderManager userLevelOrderManager;
    private final OrderUseScoreManager orderUseScoreManager;

    @PostMapping("/confirm")
    @Operation(summary = "结算，生成积分订单信息" , description = "传入下单所需要的参数进行下单")
    public ServerResponseEntity<ShopCartOrderMergerDto> confirm(@Valid @RequestBody OrderParam orderParam) {
        if (Objects.isNull(orderParam.getOrderItem())) {
            // 请选择您需要的商品进行购买
            throw new YamiShopBindException("yami.score.select.num.shop");
        }
        //pc端 立即购买
        if(Objects.isNull(orderParam.getDvyTypes()) && Objects.nonNull(orderParam.getOrderItem())){
            orderParam.setDvyTypes(Collections.singletonList(new DvyTypeDTO(orderParam.getOrderItem().getShopId(), DvyType.DELIVERY.value())));
        }
        String userId = SecurityUtils.getUser().getUserId();
        // 将要返回给前端的完整的订单信息
        ShopCartOrderMergerDto shopCartOrderMerger = new ShopCartOrderMergerDto();
        shopCartOrderMerger.setDvyTypes(orderParam.getDvyTypes());
        shopCartOrderMerger.setOrderType(OrderType.SCORE);
        shopCartOrderMerger.setMold(0);
        shopCartOrderMerger.setIsScorePay(1);
        shopCartOrderMerger.setPreSellStatus(0);
        shopCartOrderMerger.setUserId(userId);

        List<ShopCartItemDto> shopCartItemsDb = shopCartItemAdapter.getActivityShopCartItem(orderParam.getOrderItem(), orderParam.getDvyTypes(), null, userId, null);
        // pc端 购物车
        if(Objects.isNull(orderParam.getDvyTypes()) && CollectionUtil.isNotEmpty(shopCartItemsDb)){
            List<DvyTypeDTO> dvyTypes = new ArrayList<>();
            Set<Long> shopIdSet = shopCartItemsDb.stream().map(ShopCartItemDto::getShopId).collect(Collectors.toSet());
            for(Long shopId : shopIdSet) {
                dvyTypes.add(new DvyTypeDTO(shopId, DvyType.DELIVERY.value()));
            }
            orderParam.setDvyTypes(dvyTypes);
            shopCartOrderMerger.setDvyTypes(dvyTypes);
        }

        // 获取用户地址信息
        UserDeliveryInfoVO userDeliveryInfo = confirmOrderManager.getUserDeliveryInfoVO(shopCartItemsDb, userId, orderParam.getDvyTypes(), orderParam.getAddrId());

        // 筛选过滤掉不同配送的商品
        List<ShopCartItemDto> shopCartItems = confirmOrderManager.filterShopItemsByType(shopCartOrderMerger, userDeliveryInfo, shopCartItemsDb);

        // 购物车
        List<ShopCartDto> shopCarts = shopCartAdapter.getShopCarts(shopCartItems);

        // 计算运费，获取用户地址，自提信息
        userDeliveryInfo = deliveryOrderManager.calculateAndGetDeliverInfo(shopCartItems, userDeliveryInfo);

        // 当算完一遍店铺的各种满减活动时，重算一遍订单金额
        confirmOrderManager.recalculateAmountWhenFinishingCalculateShop(shopCartOrderMerger, shopCarts, userDeliveryInfo);

        // 等活动处理完之后，再插入sku的库存区域id -- 赠品、套餐和组合商品需要在marketing模块中处理
        confirmOrderManager.handleShopCartStockPoint(userDeliveryInfo, shopCarts, shopCartItemsDb, shopCartOrderMerger.getMold());

        double orderShopReduce = shopCartOrderMerger.getOrderReduce();
        // 店铺会员等级优惠计算
        if (userLevelOrderManager != null) {
            userLevelOrderManager.calShopLevelDiscount(shopCartOrderMerger);
        }
        confirmOrderManager.reCalAmountWhenFinishCalShop(shopCartOrderMerger);

        shopCartOrderMerger.setOrderShopReduce(orderShopReduce);
        // 缓存计算
        confirmOrderManager.cacheCalculatedInfo(userId, shopCartOrderMerger);
        return ServerResponseEntity.success(shopCartOrderMerger);
    }
}
